<template>
    <v-layout v-if="isLoading">
        <div style="display: flex;justify-content: center;align-items: center;height: 100vh;width: 100%;">
            <v-progress-circular indeterminate size="50" color="blue" width="1"></v-progress-circular>
        </div>
    </v-layout>
    <v-layout v-else>
        <div style="width: 100%; margin: 1%;">
            <v-card style="padding: 1%;" elevation="3">
                <v-data-table-server fixed-header style="max-height: 80vh; overflow-y: auto;"
                    v-model:items-per-page="data.itemsPerPage" :headers="data.headers" :items-length="data.totalItems"
                    :items="data.serverItems" :loading="data.loading" :search="data.search" item-value="name"
                    @update:options="loadItems">
                    <template v-slot:tfoot>
                        <tr>
                            <td>
                                <v-text-field v-model="data.name" hide-details placeholder="搜索名称..."
                                    density="compact"></v-text-field>
                            </td>
                        </tr>
                    </template>
                    <template v-slot:[`item.option`]="{ item }">
                        <v-icon @click="editSubscriber(item)">mdi-pencil</v-icon>
                    </template>
                </v-data-table-server>
                <v-dialog v-model="editDialog" max-width="500px">
                    <v-card>
                        <v-card-title>编辑教师信息</v-card-title>
                        <v-card-text>
                            <v-form @submit.prevent="saveChanges">
                                <v-text-field v-model="politics" label="政治面貌"></v-text-field>
                                <v-text-field v-model="academy" label="所处学院"></v-text-field>
                                <v-text-field v-model="researchDirection" label="研究方向"></v-text-field>
                                <v-card-actions>
                                    <v-btn @click="editDialog = false">取消</v-btn>
                                    <v-btn color="primary" type="submit">保存</v-btn>
                                </v-card-actions>
                            </v-form>
                        </v-card-text>
                    </v-card>
                </v-dialog>
            </v-card>
        </div>
    </v-layout>
</template>
<script setup lang="ts">
import { GetSubscriberInfo } from '@/controllers/subscriberController';
import { UpdateAppointedUser } from '@/controllers/userController';
import type { Subscriber } from '@/models/subscriber';
import { message } from '@/utils/message';
import { reactive, ref, watch } from 'vue';
let isLoading = ref(false)
let editDialog = ref(false)
let researchDirection = ref('')
let politics = ref('')
let academy = ref('')
let id = ref(0)
let editedSubscriber = reactive({} as Subscriber);
let data = reactive({
    itemsPerPage: 10,
    headers: [
        { title: '姓名', sortable: false, key: 'name' },
        { title: '性别', sortable: false, key: 'gender' },
        { title: '生日', sortable: false, key: 'birthday' },
        { title: '政治面貌', sortable: false, key: 'politics' },
        { title: '民族', sortable: false, key: 'nationality' },
        { title: '所处学院', sortable: false, key: 'academy' },
        { title: '电话', sortable: false, key: 'phone' },
        { title: '国籍', sortable: false, key: 'origin' },
        { title: '地址', sortable: false, key: 'address' },
        { title: '研究方向', sortable: false, key: 'researchDirection' },
        { title: '操作', sortable: false, key: 'option' },
    ],
    search: '',
    serverItems: [] as Subscriber[],
    loading: true,
    name: '',
    totalItems: 0
})

watch(() => data.name, () => {
    const currentTime = String(Date.now());
    data.search = currentTime;
});

async function getSubscriberInfo({ page, itemsPerPage, sortBy, search }: { page: number; itemsPerPage: number; sortBy: any[]; search: any }) {
    try {
        let subscriberInfo = await GetSubscriberInfo('1');
        const start = (page - 1) * itemsPerPage;
        const end = start + itemsPerPage;
        const items = subscriberInfo.slice().filter(item => {
            if (search.name && !item.name.toLowerCase().includes(search.name.toLowerCase())) {
                return false
            }
            return true
        })

        if (sortBy.length) {
            const sortKey = sortBy[0].key
            const sortOrder = sortBy[0].order
            items.sort((a, b) => {
                const aValue = a[sortKey]
                const bValue = b[sortKey]
                return sortOrder === 'desc' ? bValue - aValue : aValue - bValue
            })
        }

        const paginated = items.slice(start, end)
        return ({ items: paginated, total: items.length })
    } catch (error: any) {
        message(error.message, 'error')
    }
}
function loadItems({ page, itemsPerPage, sortBy }: { page: number; itemsPerPage: number; sortBy: any[] }) {
    data.loading = true
    getSubscriberInfo({ page, itemsPerPage, sortBy, search: { name: data.name } }).then((result) => {
        if (result) {
            data.serverItems = result.items || [];
            data.totalItems = result.total || 0;
        }
        data.loading = false
    })
}
function editSubscriber(subscriber: Subscriber) {
    editedSubscriber = { ...subscriber };
    console.log(editedSubscriber.name)
    researchDirection.value = editedSubscriber.researchDirection
    politics.value = editedSubscriber.politics
    academy.value = editedSubscriber.academy
    id.value = editedSubscriber.userId
    editDialog.value = true;
}
async function saveChanges() {
    try {
        await UpdateAppointedUser(id.value, researchDirection.value, academy.value, politics.value, false);
        editDialog.value = false;
        loadItems({ page: 1, itemsPerPage: data.itemsPerPage, sortBy: [] });
    } catch (error: any) {
        message(error.message, 'error');
    }
}
</script>
